package com.mars.ms.aqs;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * author by: mars
 * Date: 2022/4/13 11:54
 * Description: 自定义 semaphone
 */
public class SemaphoreDemo {

    static class MarsSemaphore extends AbstractQueuedSynchronizer {
        // 初始化设置一次允许执行数量
        public MarsSemaphore(int num) {
            setState(num);
        }

        // 获取请求数量
        @Override
        protected int tryAcquireShared(int arg) {
            // 获取当前数量
            int num = getState();
            if ( num == 0 ) {
                return -1;
            }
            // 计算剩余允许数量
            int left = num - 1;
            if (compareAndSetState(num,left)) {
                return left;
            }
            return -1;  // 错误返回-1
        }

        // 释放请求数量
        @Override
        protected boolean tryReleaseShared(int arg) {
            int num = getState();
            return compareAndSetState(num,num + 1);
        }
    }

    public static void main(String[] args){
        MarsSemaphore semaphore = new MarsSemaphore(3);
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                try {
                    // 调用获取，其实是调用aqs的acquireShare 并不是 重写的 tryAcquireShared,tryAcquireShared 只是编写获取线程条件
                    semaphore.acquireShared(0);
                    System.out.println("go");
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 调用释放，releaseShared 并不是 重写的 tryReleaseShared,tryReleaseShared 只是编写释放线程条件
                semaphore.releaseShared(0);
            }).start();
        }
    }
}
